<template>
  <!--权限（菜单）新增/修改Modal-->
  <a-modal
    :title="isAdd? '权限菜单新增':'权限菜单修改'"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleModalOk"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item
        label="隐藏的参数"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        style="display: none"
      >
        <a-input v-decorator="['id',{initialValue: permissionFmt.id}]"/>
      </a-form-item>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="权限名称" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-input
              v-decorator="[
                `name`,
                {
                  initialValue: permissionFmt.name,
                  rules: [
                    {
                      required: true,
                      message: '请输入权限名称'
                    },
                    {
                      validator: permissionNameValidator
                    }
                  ]
                }
              ]"
              placeholder="请输入权限名称"
              :allowClear="true"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="父节点"
            :label-col="labelCol"
            :wrapper-col="wrapperCol">
            <a-tree-select
              v-decorator="[`parentId`, { initialValue: permissionFmt.parentId }]"
              placeholder="请选择所属父节点"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :treeData="treeFmt"
              :allowClear="true"
              @change="treeChange"
            >
            </a-tree-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="唯一编码" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-input
              v-decorator="[
                `code`,
                {
                  initialValue: permissionFmt.code,
                  rules: [
                    {
                      required: true,
                      message: '请输入唯一编码'
                    },
                    {
                      validator: permissionCodeValidator
                    }
                  ]
                }
              ]"
              placeholder="请输入唯一编码，与前端vue管理页面相对应"
              :allowClear="true"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="图标类型" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-input
              v-decorator="[`icon`, { initialValue: permissionFmt.icon }]"
              placeholder="请参考Ant Design of Vue Icon，例如：shrink"
              :allowClear="true"
            >
              <a-icon slot="addonAfter" type="info-circle" @click="iconSelectOpen" />
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="菜单类型"
            :label-col="labelCol"
            :wrapper-col="wrapperCol">
            <a-select
              v-decorator="[`type`, { initialValue: permissionFmt.type }]"
              placeholder="Please select a country"
            >
              <a-select-option value="0">
                分组菜单
              </a-select-option>
              <a-select-option value="1">
                页面菜单
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="排序字段"
            :label-col="labelCol"
            :wrapper-col="wrapperCol">
            <a-input
              type="number"
              :min="1"
              :max="99"
              v-decorator="[`sort`,{initialValue: permissionFmt.sort}]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="状态"
            :label-col="labelCol"
            :wrapper-col="wrapperCol">
            <a-select
              v-decorator="[`state`,{initialValue: permissionFmt.state}]"
              placeholder="Please select a country"
            >
              <a-select-option value="1">
                启用
              </a-select-option>
              <a-select-option value="0">
                禁用
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item
            label="备注"
            :label-col="{
              xs: { span: 6 },
              sm: { span: 3 }
            }"
            :wrapper-col="{
              xs: { span: 18 },
              sm: { span: 21 }
            }"
          >
            <a-textarea
              :rows="3"
              v-decorator="[
                'remark',
                { initialValue: permissionFmt.remark }
              ]"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <IconSelectorModal ref="iconModal" @iconSel="iconSelect" ></IconSelectorModal>
  </a-modal>
</template>

<script>
import api from '../system'
import { emptyObject } from '@/utils/samsUtil'
import { treePermissionConvert } from '@/utils/antUtil'
import IconSelectorModal from './IconSelectorModal'

// 权限（菜单）新增/修改Modal
export default {
  name: 'PermissionModalModify',
  components: { IconSelectorModal },
  data () {
    return {
      isAdd: true,
      visible: false,
      confirmLoading: false,
      width: 1000,
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 18 }
      },
      permission: {},
      level: 1,
      parentIds: '0',
      treeData: []
    }
  },
  computed: {
    treeFmt () {
      let { treeData } = this
      treeData = treeData || []
      const tree = treePermissionConvert(treeData)
      return tree
    },
    permissionFmt () {
      let { permission } = this
      permission = permission || {}
      const fmt = {
        ...permission,
        type: permission.type === 0 ? '0' : '1',
        state: permission.state === 0 ? '0' : '1',
        parentId: permission.parentId ? permission.parentId + '' : undefined
      }
      return fmt
    }
  },
  created () {
    this.queryGroupMenuTree()
  },
  methods: {
    // Modal show
    showModal (param = {}) {
      this.queryGroupMenuTree()
      this.restForm()
      this.isAdd = emptyObject(param) && emptyObject(param.id)
      this.level = param.level || 1
      this.parentIds = param.parentIds || '0'
      this.permission = param
      this.visible = true
    },
    // Modal hide
    hideModal () {
      this.visible = false
    },
    // Modal 确定按钮--保存
    handleModalOk () {
      this.form.validateFields((error, values) => {
        if (error === null) {
          const param = {
            ...values,
            level: this.level,
            parentIds: this.parentIds
          }
          let url = api.permission.add
          if (!this.isAdd) {
            url = api.permission.update
            if (values.id + '' === values.parentId + '') {
              return this.$message.warning('不能选择自身为父节点，请选择正确的父节点再提交！！！')
            }
          }
          this.axios.post(url, param)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success('保存成功')
                this.$emit('refresh')
                this.hideModal()
              } else {
                this.$message.error('保存失败：' + response.message)
              }
            })
            .catch((error) => {
              this.$message.error('保存异常：' + error)
            })
        } else {
          this.$message.error('提交异常，请检查是否有参数未校验成功')
        }
      })
    },
    // 取消按钮
    handleCancel () {
      this.hideModal()
    },
    // Form 表单数据初始化方法 还原
    restForm () {
      this.form.resetFields()
    },
    // IconSelectorModal show
    iconSelectOpen () {
      const value = this.form.getFieldValue('icon')
      this.$refs.iconModal.showModal(value)
    },
    // IconSelectorModal选中的icon
    iconSelect (icon) {
      this.form.setFieldsValue({ 'icon': icon })
    },
    // 加载treeData
    queryGroupMenuTree () {
      this.axios.post(api.permission.getGroupMenuTree)
        .then((response) => {
          console.log('Permission-父节点请求结果：', response)
          this.treeData = response.data
        })
        .catch((error) => {
          console.log('Permission-父节点请求异常了：', error)
        })
    },
    // tree改变事件，通过节点获取到内部参数，如下获取到存储在tree中的level数据
    treeChange (value, label, extra) {
      if (!value) {
        this.level = 1
        this.parentIds = '0'
        return false
      }
      const dataRef = extra.triggerNode && extra.triggerNode.dataRef || {}
      const level = dataRef.label || 0
      const parentIds = dataRef.parentIds || 0
      this.level = level + 1
      this.parentIds = parentIds + ',' + value
      if (!this.isAdd && this.form.getFieldValue('id') + '' === value) {
        return this.$message.warning('不能选择自身为父节点')
      }
    },
    // 校验-权限名称校验
    permissionNameValidator (rule, value, callback) {
      if (emptyObject(value)) {
        callback()
        return
      }
      this.axios.post(api.permission.permissionNameUnique,
        { id: this.form.getFieldValue('id'), name: value })
        .then((response) => {
          if (response.code === 200) {
            callback()
          } else {
            // eslint-disable-next-line
            callback('该权限名称已存在')
          }
        })
    },
    // 校验-权限code/唯一编码校验
    permissionCodeValidator (rule, value, callback) {
      if (emptyObject(value)) {
        callback()
        return
      }
      this.axios.post(api.permission.permissionCodeUnique,
        { id: this.form.getFieldValue('id'), code: value })
        .then((response) => {
          if (response.code === 200) {
            callback()
          } else {
            // eslint-disable-next-line
            callback('该唯一编码已存在')
          }
        })
    }
  }
}
</script>
